<template>
<!-- 小时工 -->
  <div class="submit-box head-line">
    <AddressCard :addr="addressData" />
    <div class="card-shadow">
      <view class="weui-cell weui-cell_select">
        <view class="weui-cell__hd">
          <view class="weui-label">选择服务价格</view>
        </view>
        <view class="weui-cell__bd">
          <picker @change="bindPriceChange" :value="priceIndex" :range="priceArr">
            <view class="weui-select text-right">{{priceArr[priceIndex]}}</view>
          </picker>
        </view>
      </view>
    </div>
    <div class="card-shadow">
      <navigator :url="selectStartTimeUrl" class="weui-cell weui-cell_select">
        <view class="weui-cell__hd">
          <view class="weui-label">选择服务时间</view>
        </view>
        <view class="weui-cell__bd">
          <view class="weui-select text-right">{{serviceStartTime}}</view>
        </view>
      </navigator>
    </div>
    <div class="card-shadow">
      <view class="weui-cell weui-cell_select" @tap="hardSelectTime">
        <view class="weui-cell__hd">
          <view class="weui-label">选择服务时长</view>
        </view>
        <view class="weui-cell__bd">
          <view class="weui-select text-right">{{serviceTime}}小时</view>
        </view>
      </view>
    </div>
    <PopLayer
      animation="dialog-bounce-bottom"
      :pdata="serviceTimeData"
      :visible.sync="popVisible"
      @change="selectTimeChange"
    />
    <div class="card-shadow">
      <div class="weui-cell">
        <div class="weui-cell__bd">
          <textarea
            class="weui-textarea default-color"
            name="remarks"
            v-model="remarks"
            placeholder="如有其它需求请在此填写备注"
            @input="textareaInput"
            :maxlength="maxlength"/>
          <div class="weui-textarea-counter">{{nowLength}}/{{maxlength}}</div>
        </div>
      </div>
    </div>
    <div class="btn-full-box">
      <view class="btn-full" @tap="submit">立即预定</view>
    </div>
  </div>
</template>
<script>
import getServicePrice from '@/interface/getServicePrice'
import getAddressList from '@/interface/address/getAddressList'
import dateUtil from '@/utils/dateUtil'
import PopLayer from '@/components/PopLayer/index'
import AddressCard from '@/components/AddressCard/index'
import saveOrder from '@/interface/order/saveOrder'
import {serviceTypeData} from '@/config'
import payFun from '@/utils/pay'

export default {
  components: { PopLayer, AddressCard },
  data () {
    const tomDate = dateUtil.addDays(new Date(), 1)
    const tomDateStr = dateUtil.format(tomDate, 'yyyy-MM-dd')
    return {
      isSubmit: false,
      addressData: {},
      priceValue: ['', ''],
      priceArr: [ `元/小时`, `元/小时` ],
      priceIndex: 0,
      popVisible: false,
      serviceTimeData: {
        title: '请选择服务时长',
        range: [
          { time: 2, money: '', checked: true, disabled: false },
          { time: 2.5, money: '', checked: false, disabled: false },
          { time: 3, money: '', checked: false, disabled: false },
          { time: 3.5, money: '', checked: false, disabled: false },
          { time: 4, money: '', checked: false, disabled: false },
          { time: 4.5, money: '', checked: false, disabled: false }
        ]
      },
      serviceStartTime: `${tomDateStr} 08:00`,
      remarks: '',
      nowLength: 0,
      maxlength: 50,
    }
  },
  computed: {
    serviceTime () {
      const item = this.serviceTimeData.range.find(v => v.checked)
      return item ? item.time : ''
    },
    selectStartTimeUrl () {
      return `/pages/selectDate/main?select=${encodeURIComponent(this.serviceStartTime)}`
    }
  },
  watch: {
    priceIndex () {
      this.setPriceRange()
    },
    serviceStartTime (val) {
      const timeArr = val.split(' ')[1].split(':')
      const hour = timeArr[1] === '30' ? Number(timeArr[0]) + 0.5 : Number(timeArr[0])
      // 晚上20点后不能预约
      const timeLength = 20 - hour
      const arr = [...this.serviceTimeData.range]
      arr.map(v => {
        if (v.time > timeLength) {
          v.disabled = true
          v.checked = false
        } else {
          v.disabled = false
        }
        return v
      })
      this.serviceTimeData.range = arr
    }
  },
  methods: {
    setPriceRange () {
      const arr = [...this.serviceTimeData.range]
      arr.map(v => {
        v.money = v.time * this.priceValue[this.priceIndex]
        return v
      })
      this.serviceTimeData.range = arr
    },
    hadAddress () {
      const addr = this.addressData || {}
      return addr.custName && addr.areaCode && addr.phone
    },
    bindPriceChange (e) {
      this.priceIndex = Number(e.mp.detail.value)
    },
    hardSelectTime () {
      this.popVisible = true
    },
    textareaInput (e) {
      this.nowLength = e.mp.detail.value.length
    },
    selectTimeChange (index) {
      this.serviceTimeData.range = this.serviceTimeData.range.map((v, i) => {
        v.checked = i === index
        return v
      })
    },
    submit () {
      if (!this.hadAddress()) {
        this.dialog.showToast('请先填写地址')
        return
      }
      if (!this.serviceTime) {
        this.dialog.showToast('请选择服务时长')
        return
      }
      this.isSubmit = true
      saveOrder({
        addressId: this.addressData.id,
        serviceType: serviceTypeData.xsg,
        serviceDate: this.serviceStartTime,
        servicePrice: this.priceValue[this.priceIndex],
        serviceDuration: this.serviceTime,
        // overtimeStatus: 0,
        remarks: this.remarks,
        orderPrice: this.priceValue[this.priceIndex] * this.serviceTime
      }).then(data => {
        payFun({ orderNo: data.orderNo }, () => {
          const orderStatus = 1;
          this.goStatusPage('success', '支付', orderStatus)
        }, () => {
          const orderStatus = 0;
          this.goStatusPage('error', '支付', orderStatus)
        })
      }).catch(msg => this.dialog.showToast(msg || '保存失败'))
        .finally(() => { this.isSubmit = false })
    },
    getPrice () {
      getServicePrice().then(data => {
        const { hourFirstPrice, hourSecondPrice } = data
        this.priceValue = [hourFirstPrice, hourSecondPrice]
        this.priceArr = [`${hourFirstPrice}元/小时`, `${hourSecondPrice}元/小时`]
        this.setPriceRange()
      })
    }
  },
  beforeMount () {
    this.checkLogin()
  },
  mounted () {
    getAddressList({isDefault: true}).then(data => {
      this.addressData = data || {}
    })
    this.getPrice()
  },
  onShow () {
    const {store} = this.globalData
    const hourWorker = store.hourWorker

    if (hourWorker) {
      this.serviceStartTime = `${hourWorker.date} ${hourWorker.time}`
      this.globalData.store.hourWorker = null
    }
    if (store.selectAddr) {
      this.addressData = store.selectAddr
      this.globalData.store.selectAddr = null
    }else if(!this.hadAddress()){
      getAddressList({isDefault: true}).then(data => {
        this.addressData = data || {}
      })
    }
  }
}
</script>
<style lang="less">
page{
  background-color: #f9f9f9;
}
.submit-box .weui-cell {
  .weui-label {
    width: 240upx;
  }
}
</style>